package game;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;

import javax.imageio.ImageIO;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import game.Sprites.SpriteSheet;
import game.Weapons.LoadWeapons;
import net.sf.image4j.codec.bmp.BMPDecoder;
import org.apache.commons.configuration.ConfigurationException;
import org.json.simple.parser.ParseException;

public class GameState implements ActionListener {
    public int GAME_STATE = 0;              // 0 menu, 1 playing, 2 configuration menu

    public JFrame f;
    public JPanel buttonsPackMenu;          // Principal menu panel
    public JPanel buttonsPackConf;          // Configuration menu panel
    public JPanel buttonsPackNewGame;       // New game menu panel

    public static Configuration conf;
    public static MusicPlayer mP;
    public static Thread musicThread;

    /**
     * Game start call
     *
     * @param args
     * @throws ConfigurationException
     * @throws IOException
     */
    public static void main(String args[]) throws ConfigurationException, IOException, ParseException, ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, URISyntaxException, LineUnavailableException, UnsupportedAudioFileException {
        // activate opengl
        System.setProperty("sun.java2d.opengl", "True");

        // set system look and feel
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        GameState gameState = new GameState();



        mP = new MusicPlayer();
        // Music player object and thread
        musicThread = new Thread(mP);
        musicThread.start();
        // Load weapons file and info
        LoadWeapons lw = new LoadWeapons();

        // Load game configuration
        conf = new Configuration();
    }

    GameState() throws IOException {
        GAME_STATE = 0;
        f = new JFrame("CS2D");
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);            // Fullscreen
        //f.setUndecorated(true); 							// Frame without contours
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //TODO: Revisar
        BufferedImage img = ImageIO.read(getClass().getClassLoader().getResourceAsStream("Sprites/hud/pointer.png"));
        try {
            SpriteSheet pointers = new SpriteSheet(img, 2, 2);
            Toolkit kit = Toolkit.getDefaultToolkit();
            //Cursor cursor = kit.createCustomCursor(pointers.get(0), new Point((int)pointers.get(0).getWidth() / 2 - 7, (int)pointers.get(0).getHeight() / 2 - 7), "myCursor");
            //f.setCursor(cursor);
        } catch (Exception e) {
            e.printStackTrace();
        }


        menu();
    }

    /**
     *
     */
    public void menu() {
        // Buttons list
        buttonsPackMenu = new JPanel(new GridLayout(3, 1, 0, 30));

        // New Game Button
        JButton iniciar = new JButton("NUEVA PARTIDA");
        try {
            iniciar = new JButton(new ImageIcon(ImageIO.read(getClass().getClassLoader().
                    getResource("Images/Buttons/ButtonInitGame.bmp"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        iniciar.setOpaque(false);
        iniciar.setContentAreaFilled(false);
        iniciar.setBorderPainted(false);
        iniciar.setActionCommand("NUEVA PARTIDA");
        iniciar.addActionListener(this);

        // Configuration Button
        JButton conf = new JButton("CONFIGURACION");
        try {
            conf = new JButton(new ImageIcon(ImageIO.read(getClass().getClassLoader().
                    getResource("Images/Buttons/ButtonInitGame.bmp"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        conf.setOpaque(false);
        conf.setContentAreaFilled(false);
        conf.setBorderPainted(false);
        conf.setActionCommand("CONFIGURACION");
        conf.addActionListener(this);

        // Close button
        JButton salir = new JButton("SALIR");
        try {
            salir = new JButton(new ImageIcon(ImageIO.read(getClass().getClassLoader().
                    getResource("Images/Buttons/ButtonInitGame.bmp"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        salir.setOpaque(false);
        salir.setContentAreaFilled(false);
        salir.setBorderPainted(false);
        salir.setActionCommand("SALIR");
        salir.addActionListener(this);


        Panel panel = new Panel();
        buttonsPackMenu.setOpaque(false);
        panel.add(buttonsPackMenu);
        panel.setLayout(new GridBagLayout());
        f.add(panel);
        buttonsPackMenu.add(iniciar);
        buttonsPackMenu.add(conf);
        buttonsPackMenu.add(salir);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }


    @Override
    public void actionPerformed(ActionEvent ae) {
        String comStr = ae.getActionCommand();
        if (comStr.equals("NUEVA PARTIDA")) {
            GAME_STATE = 1;
            //mP.stopPlay();    // Parar musica de background

            buttonsPackMenu.setVisible(false);
            //changePanelToNewGame();
            // Llamada a iniciar juego
            Main.main(f);
        } else if (comStr.equals("CONFIGURACION")) {
            GAME_STATE = 2;
            buttonsPackMenu.setVisible(false);

            // Cambiar panel
            try {
                changePanelToConf();
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }

            // Llamada a configuracion
        } else if (comStr.equals("SALIR")) {
            System.exit(0);
        } else if (comStr.equals("VOLVER")) {
            buttonsPackConf.setVisible(false);
            buttonsPackNewGame.setVisible(false);
            buttonsPackMenu.setVisible(true);
        } else if (comStr.equals("GUARDAR")) {

        }
    }

    public void changePanelToNewGame() {
        // Buttons list
        buttonsPackNewGame = new JPanel(new GridLayout(3, 1, 0, 30));

        // Configuration Button
        JButton conf = new JButton("BLA BLA");
        try {
            conf = new JButton(new ImageIcon(ImageIO.read(getClass().getClassLoader().
                    getResource("Images/Buttons/ButtonInitGame.bmp"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        conf.setOpaque(false);
        conf.setContentAreaFilled(false);
        conf.setBorderPainted(false);
        conf.setActionCommand("BLA BLA");
        conf.addActionListener(this);

        // Close button
        JButton volver = new JButton("VOLVER");
        try {
            volver = new JButton(new ImageIcon(ImageIO.read(getClass().getClassLoader().
                    getResource("Images/Buttons/ButtonInitGame.bmp"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        volver.setOpaque(false);
        volver.setContentAreaFilled(false);
        volver.setBorderPainted(false);
        volver.setActionCommand("VOLVER");
        volver.addActionListener(this);


        Panel panel = new Panel();
        buttonsPackNewGame.setOpaque(false);
        panel.add(buttonsPackNewGame);
        panel.setLayout(new GridBagLayout());
        buttonsPackNewGame.add(conf);
        buttonsPackNewGame.add(volver);
        f.add(panel);
    }

    public void changePanelToConf() throws FileNotFoundException, IOException, ParseException {
        // PANEL
        GridLayout gl = new GridLayout(3, 1, 0, 30);
        buttonsPackConf = new JPanel(gl);
        //jp.setPreferredSize(new Dimension(500,500));
        buttonsPackConf.setBackground(Color.darkGray);

        // CARGAR DATOS
        String res = conf.getResolution();
        int vol = Integer.parseInt(conf.getVolumeMaster());

        // SLIDER
        JSlider volumen = new JSlider(JSlider.HORIZONTAL, 0, 100, vol);
        int value = volumen.getValue();
        JTextField valueP = new JTextField(5);

        volumen.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent ce) {
                valueP.setText("" + volumen.getValue());
            }
        });
        buttonsPackConf.add(valueP);
        buttonsPackConf.add(volumen);

        // BOTONES
        JButton reso = new JButton("RESOLUCION");
        buttonsPackConf.add(reso);
        JButton volver = new JButton("VOLVER");
        buttonsPackConf.add(volver);
        volver.addActionListener(this);
        f.add(buttonsPackConf);
    }

}

   